import {Component, OnInit} from '@angular/core';
import {Subscription} from 'rxjs/Subscription';
import {NormalService} from '../../../apiServices/normal.service';

@Component({
    selector: 'exchange-voucher',
    templateUrl: './exchange-voucher.template.html'
})
export class ExchangeVoucherComponent implements OnInit{
    public language: string = 'en';
    public user: any;
    public voucher: any = {};
    public userSubscription: Subscription;
    isSubmitvoucher: any = {en: 'Voucher submit success', zh: '兑换券提交成功'};
    submitvoucherFail: any = {en: 'Voucher submit failer,please try again later', zh: '兑换券提交失败，请稍后重试'}
 
    constructor(
        private normalService: NormalService
    ) {
        this.language = normalService.language;
        if(normalService.isLogin()){
                normalService.getuser().catch((error) => {
                    alert(normalService.getErrors(error));
                });
           
        }
        this.userSubscription = normalService.user$.subscribe(user=>{
            this.user = user;
        });
        normalService.logout$.subscribe(logout=>{
            console.log(logout);
        });
        // 初始化 voucher 对象的state 为 0
        this.voucher.state = 0;
    }

    submitVoucher(): void {
        console.log(this.voucher);
        this.normalService.updateuser(this.user._id, {
            '$set': {'updatedAt': new Date()},
            '$push': {
                'exchange': this.voucher
            }
        },{}).then(newUser => {
            if(this.normalService.lang == 'en'){
                alert(this.isSubmitvoucher.en);
            }
            if(this.normalService.lang == 'zh'){
                alert(this.isSubmitvoucher.zh);
            } 
        }).catch(e => {
            if(this.normalService.lang == 'en'){
                alert(this.submitvoucherFail.en);
            }
            if(this.normalService.lang == 'zh'){
                alert(this.submitvoucherFail.zh);
            }  
        });
    }
    ngOnInit(): void {
        
    }
}